package com.feeyo.groundservice.recordnfc.activity.view

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableLongState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ScreenUtils
import com.feeyo.groundservice.base_util.CallbackWithData
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.dealString
import com.feeyo.groundservice.base_util.getConfirmDlg
import com.feeyo.groundservice.base_util.getRouterPath
import com.feeyo.groundservice.base_util.toastCenter
import com.feeyo.groundservice.composewidget.util.EmptyListView
import com.feeyo.groundservice.composewidget.util.dimenToDp
import com.feeyo.groundservice.composewidget.util.dimenToSp
import com.feeyo.groundservice.composewidget.util.drawableToPainter
import com.feeyo.groundservice.composewidget.util.intervalClick
import com.feeyo.groundservice.composewidget.util.pxToDp
import com.feeyo.groundservice.composewidget.util.toComposeColor
import com.feeyo.groundservice.composewidget.view.constant.ComposePosition
import com.feeyo.groundservice.composewidget.view.refreshlayout.PullToRefreshLayout
import com.feeyo.groundservice.composewidget.view.refreshlayout.rememberRefreshLayoutState
import com.feeyo.groundservice.composewidget.view.sidemenu.ChainScrollableComponentState
import com.feeyo.groundservice.composewidget.view.sidemenu.SlideMenu
import com.feeyo.groundservice.composewidget.view.tab.SwitchTab
import com.feeyo.groundservice.composewidget.view.title_bar.CommonTitleView
import com.feeyo.groundservice.composewidget.view.util.HorizontalSpace
import com.feeyo.groundservice.recordnfc.R
import com.feeyo.groundservice.recordnfc.activity.NfcLogActivity
import com.feeyo.groundservice.recordnfc.base.refreshState
import com.feeyo.groundservice.recordnfc.constant.AttachResourceType
import com.feeyo.groundservice.recordnfc.constant.RecordCardPath
import com.feeyo.groundservice.recordnfc.constant.RecorderType
import com.feeyo.groundservice.recordnfc.constant.ResourceType
import com.feeyo.groundservice.recordnfc.constant.getTabMenus
import com.feeyo.groundservice.recordnfc.constant.statusBarColor
import com.feeyo.groundservice.recordnfc.dlg.NfcBindDetailPopView
import com.feeyo.groundservice.recordnfc.model.NfcBindItemBO
import com.feeyo.groundservice.recordnfc.model.TaskItemBO
import com.feeyo.groundservice.recordnfc.viewmodel.RecorderCardViewModel
import com.lxj.xpopup.XPopup

/**
 *作者：70893 on 2025-10-12
 *描述：
 */


@Composable
fun NfcBindMainView() {

    val defaultIndex = 0
    val mCurrentSelectTab = remember { mutableIntStateOf(defaultIndex) }//当前选中的tab
    val viewModel: RecorderCardViewModel = viewModel()

    Column(
        modifier = Modifier.fillMaxSize().background(color = R.color.gray_EE.toComposeColor())
    ) {
        CommonTitleView(
            title = "NFC卡管理",
            bg = statusBarColor.toComposeColor(),
            topPadding = BarUtils.getStatusBarHeight(),
            onBack = {
                ActivityUtils.getTopActivity()?.finish()
            }, rightContent = {
                Icon(
                    painter = R.drawable.icon_search.drawableToPainter(),
                    contentDescription = null,
                    modifier = Modifier.size(R.dimen.d15.dimenToDp())
                        .intervalClick {
                            RecordCardPath.SearchActivity.getRouterPath().navigation()
                        },
                    tint = R.color.white.toComposeColor()
                )
            })

        //tab
        Row(
            modifier = Modifier.background(color = R.color.white.toComposeColor())
                .padding(vertical = R.dimen.d4.dimenToDp()),
        ) {
            HorizontalSpace(R.dimen.d10.dimenToDp())
            Spacer(modifier = Modifier.weight(1f))//占位的
            SwitchTab(
                tabRowItems = getTabMenus(),
                onSelectIndex = {
                    mCurrentSelectTab.intValue = it
                },
                defaultIndex = defaultIndex,
                bottomHeight = R.dimen.d48.dimenToDp(),
                bottomBgColor = R.color.gray_EE.toComposeColor(),
                bottomCornerRadius = 0.dp,
                selectedTextColor = statusBarColor.toComposeColor(),
                unSelectedTextColor = R.color.black_27.toComposeColor().copy(alpha = 0.55f),
                selectedTextSize = R.dimen.d16.dimenToDp(),
                unSelectedTextSize = R.dimen.d15.dimenToDp(),
                padding = 0.dp,
                slideBarGapWidth = R.dimen.d10.dimenToDp(),
                slideBarWidth = (ScreenUtils.getScreenWidth()
                    .pxToDp() - R.dimen.d20.dimenToDp() - R.dimen.d10.dimenToDp() * (getTabMenus().size - 1)) / getTabMenus().size,
                slideBarBgColor = statusBarColor.toComposeColor().copy(alpha = 0.3f),
                slideBarCornerRadius = R.dimen.d6.dimenToDp(),
            )
            Spacer(modifier = Modifier.weight(1f))
            HorizontalSpace(R.dimen.d10.dimenToDp())
        }

        //数量
        Text(
            text = "数量：${viewModel.nfcBindList.value?.size ?: 0}",
            fontSize = R.dimen.d14.dimenToSp(),
            fontWeight = FontWeight.W500,
            color = R.color.black_33.toComposeColor(),
            textAlign = TextAlign.Start,
            modifier = Modifier.fillMaxWidth()
                .background(color = R.color.white.toComposeColor())
                .padding(horizontal = R.dimen.d15.dimenToDp(), vertical = R.dimen.d10.dimenToDp())
        )

        when (mCurrentSelectTab.intValue) {
            RecorderType.PERSON.index -> // 人员
                PersonNfcLog()

            RecorderType.CAR.index -> //车辆
                CarNfcLog()

            RecorderType.TASK.index -> //任务
                TaskNfcLog()

            else -> {}
        }
    }
}

@Composable
private fun ColumnScope.PersonNfcLog() {

    val viewModel: RecorderCardViewModel = viewModel()
    val refreshFlag = remember { mutableLongStateOf(System.currentTimeMillis()) }

    NfcLogActivity.currentRefreshFlag = refreshFlag

    val data = viewModel.nfcBindList.value ?: emptyList()

    PullToRefreshLayout(
        modifier = Modifier.fillMaxSize(),
        refreshLayoutState = rememberRefreshLayoutState {
            //编写刷新逻辑
            refreshState = this
            refreshFlag.longValue = System.currentTimeMillis()
        }
    ) {
        Column(
            Modifier.fillMaxSize()
        ) {
            //表头
            PersonItemView("卡号", "姓名", R.color.gray_EE)

            //内容
            LazyColumn(
                modifier = Modifier.fillMaxSize().background(R.color.white.toComposeColor())
            ) {
                if (data.isEmpty()) {
                    item {
                        Box(
                            modifier = Modifier.fillMaxWidth().height(R.dimen.d200.dimenToDp())
                                .background(R.color.white.toComposeColor()),
                            contentAlignment = Alignment.Center
                        ) {
                            EmptyListView()
                        }
                    }
                } else {
                    itemsIndexed(data, key = { index, it -> it.id }) { index, it ->
                        val bg = if (index % 2 == 0) R.color.white else R.color.gray_EE
                        PersonItemView(
                            it.nfc, it.personName.dealString(), bg, false,
                            onclick = { showDetail(it, refreshFlag) })
                    }
                }
            }
        }
    }

    LaunchedEffect(key1 = refreshFlag.longValue) {
        viewModel.getNfcBind(nfcType = RecorderType.PERSON)
    }
}

@Composable
private fun CarNfcLog() {

    val viewModel: RecorderCardViewModel = viewModel()
    val refreshFlag = remember { mutableLongStateOf(System.currentTimeMillis()) }
    NfcLogActivity.currentRefreshFlag = refreshFlag

    val data = viewModel.nfcBindList.value ?: emptyList()

    PullToRefreshLayout(
        modifier = Modifier.fillMaxSize(),
        refreshLayoutState = rememberRefreshLayoutState {
            //编写刷新逻辑
            refreshState = this
            refreshFlag.longValue = System.currentTimeMillis()
        }
    ) {
        Column(
            Modifier.fillMaxSize()
        ) {
            //表头
            CarouselItemView("卡号", "车牌号", R.color.gray_EE)

            //内容
            LazyColumn(
                modifier = Modifier.fillMaxSize().background(R.color.white.toComposeColor())
            ) {
                if (data.isEmpty()) {
                    item {
                        Box(
                            modifier = Modifier.fillMaxWidth().height(R.dimen.d200.dimenToDp())
                                .background(R.color.white.toComposeColor()),
                            contentAlignment = Alignment.Center
                        ) {
                            EmptyListView()
                        }
                    }
                } else {
                    itemsIndexed(data, key = { index, it -> it.id }) { index, it ->
                        val bg = if (index % 2 == 0) R.color.white else R.color.gray_EE
                        CarouselItemView(
                            it.nfc, it.carNum.dealString(), bg, false,
                            onclick = { showDetail(it, refreshFlag) })
                    }
                }
            }
        }
    }

    LaunchedEffect(key1 = refreshFlag.longValue) {
        viewModel.getNfcBind(nfcType = RecorderType.CAR)
    }
}

@Composable
private fun ColumnScope.TaskNfcLog() {

    val viewModel: RecorderCardViewModel = viewModel()
    val refreshFlag = remember { mutableLongStateOf(System.currentTimeMillis()) }
    NfcLogActivity.currentRefreshFlag = refreshFlag

    val data = viewModel.nfcBindList.value ?: emptyList()

    //侧滑状态
    val states = remember { mutableStateListOf<ChainScrollableComponentState>() }

    PullToRefreshLayout(
        modifier = Modifier.fillMaxSize(),
        refreshLayoutState = rememberRefreshLayoutState {
            //编写刷新逻辑
            refreshState = this
            refreshFlag.longValue = System.currentTimeMillis()
        }
    ) {
        Column(
            Modifier.fillMaxSize()
        ) {
            //表头
            TaskItemView("卡号", "任务", "位置", R.color.gray_EE)

            //内容
            LazyColumn(
                modifier = Modifier.fillMaxSize().background(R.color.white.toComposeColor())
            ) {
                if (data.isEmpty()) {
                    item {
                        Box(
                            modifier = Modifier.fillMaxWidth().height(R.dimen.d200.dimenToDp())
                                .background(R.color.white.toComposeColor()),
                            contentAlignment = Alignment.Center
                        ) {
                            EmptyListView()
                        }
                    }
                } else {
                    itemsIndexed(data, key = { index, it -> it.id }) { index, item ->
                        val bg = if (index % 2 == 0) R.color.white else R.color.gray_EE
                        val menuWidth = R.dimen.d50.dimenToDp()

                        SlideMenu(
                            minScrollPosition = 0.dp,
                            maxScrollPosition = menuWidth,
                            contentIsMove = true,
                            composePosition = ComposePosition.End,
                            modifier = Modifier.fillMaxWidth(),
                            onOpenOrClose = { state ->
                                //遍历state，把不是自己的都复原
                                states.forEach {
                                    if (it != state) {
                                        it.setScrollPositionWithAnimate(it.maxPx)
                                    }
                                }
                            },
                            backgroundContent = {
                                states.add(it)
                                Box(
                                    modifier = Modifier.width(menuWidth).fillMaxHeight()
                                        .background(
                                            color = R.color.red_FF3141.toComposeColor()
                                        )
                                        .intervalClick {
                                            it.closeMenu()
                                            //加任务
                                            appendTask(
                                                viewModel = viewModel,
                                                filterTask = data.filter { it.nfc == item.nfc }
                                                    .map { it.long_id },//屏蔽已有任务
                                                item = item,
                                                onSuccess = {
                                                    refreshFlag.longValue =
                                                        System.currentTimeMillis()
                                                }
                                            )
                                        },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = "加任务",
                                        fontSize = R.dimen.d14.dimenToSp(),
                                        color = R.color.white.toComposeColor(),
                                    )
                                }
                            }
                        ) {
                            TaskItemView(
                                item.nfc,
                                item.taskName.dealString(),
                                item.taskLinkName.dealString(),
                                bg,
                                false,
                                onclick = {
                                    it.closeMenu()
                                    showDetail(item, refreshFlag)
                                })
                        }
                    }
                }
            }
        }
    }

    LaunchedEffect(key1 = refreshFlag.longValue) {
        viewModel.getNfcBind(nfcType = RecorderType.TASK)
    }
}

@Composable
private fun PersonItemView(
    nfc: String,
    name: String,
    bg: Int = R.color.white,
    isTitle: Boolean = true,
    onclick: () -> Unit = {}
) {
    Row(
        Modifier.fillMaxWidth().background(bg.toComposeColor()).intervalClick { onclick() }
    ) {
        Text(
            text = nfc.dealString(),
            fontSize = if (isTitle) R.dimen.d15.dimenToSp() else R.dimen.d14.dimenToSp(),
            fontWeight = if (isTitle) FontWeight.W500 else FontWeight.W400,
            color = if (isTitle) R.color.black_33.toComposeColor() else R.color.black_66.toComposeColor(),
            textAlign = TextAlign.Center,
            modifier = Modifier
                .weight(1f)
                .padding(vertical = R.dimen.d10.dimenToDp())
        )

        Text(
            text = name.dealString(),
            fontSize = if (isTitle) R.dimen.d15.dimenToSp() else R.dimen.d14.dimenToSp(),
            fontWeight = if (isTitle) FontWeight.W500 else FontWeight.W400,
            color = if (isTitle) R.color.black_33.toComposeColor() else R.color.black_66.toComposeColor(),
            textAlign = TextAlign.Center,
            modifier = Modifier
                .weight(1f)
                .padding(vertical = R.dimen.d10.dimenToDp())
        )
    }
}

@Composable
private fun CarouselItemView(
    nfc: String,
    car: String,
    bg: Int = R.color.white,
    isTitle: Boolean = true,
    onclick: () -> Unit = {}
) {
    Row(
        Modifier.fillMaxWidth().background(bg.toComposeColor()).intervalClick { onclick() }
    ) {
        Text(
            text = nfc.dealString(),
            fontSize = if (isTitle) R.dimen.d15.dimenToSp() else R.dimen.d14.dimenToSp(),
            fontWeight = if (isTitle) FontWeight.W500 else FontWeight.W400,
            color = if (isTitle) R.color.black_33.toComposeColor() else R.color.black_66.toComposeColor(),
            textAlign = TextAlign.Center,
            modifier = Modifier
                .weight(1f)
                .padding(vertical = R.dimen.d10.dimenToDp())
        )

        Text(
            text = car.dealString(),
            fontSize = if (isTitle) R.dimen.d15.dimenToSp() else R.dimen.d14.dimenToSp(),
            fontWeight = if (isTitle) FontWeight.W500 else FontWeight.W400,
            color = if (isTitle) R.color.black_33.toComposeColor() else R.color.black_66.toComposeColor(),
            textAlign = TextAlign.Center,
            modifier = Modifier
                .weight(1f)
                .padding(vertical = R.dimen.d10.dimenToDp())
        )
    }
}

@Composable
private fun TaskItemView(
    nfc: String,
    task: String,
    position: String,
    bg: Int = R.color.white,
    isTitle: Boolean = true,
    onclick: () -> Unit = {}
) {
    Row(
        Modifier.width(ScreenUtils.getScreenWidth().pxToDp())
            .background(bg.toComposeColor()).intervalClick { onclick() },
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = nfc.dealString(),
            fontSize = if (isTitle) R.dimen.d15.dimenToSp() else R.dimen.d14.dimenToSp(),
            fontWeight = if (isTitle) FontWeight.W500 else FontWeight.W400,
            color = if (isTitle) R.color.black_33.toComposeColor() else R.color.black_66.toComposeColor(),
            textAlign = TextAlign.Center,
            modifier = Modifier.weight(1f).padding(vertical = R.dimen.d10.dimenToDp())

        )

        Text(
            text = task.dealString(),
            fontSize = if (isTitle) R.dimen.d15.dimenToSp() else R.dimen.d14.dimenToSp(),
            fontWeight = if (isTitle) FontWeight.W500 else FontWeight.W400,
            color = if (isTitle) R.color.black_33.toComposeColor() else R.color.black_66.toComposeColor(),
            textAlign = TextAlign.Center,
            modifier = Modifier.weight(1f).padding(vertical = R.dimen.d10.dimenToDp())
        )

        Text(
            text = position.ifEmpty { "不限" },
            fontSize = R.dimen.d14.dimenToSp(),
            fontWeight = FontWeight.W400,
            color = R.color.black_66.toComposeColor(),
            textAlign = TextAlign.Center,
            modifier = Modifier.weight(1f).padding(vertical = R.dimen.d10.dimenToDp())
        )
    }
}

internal fun showDetail(data: NfcBindItemBO, refreshFlag: MutableLongState) {
    ActivityUtils.getTopActivity()?.let {
        XPopup.Builder(it)
            .dismissOnBackPressed(true)
            .dismissOnTouchOutside(true)
            .asCustom(NfcBindDetailPopView(it).apply {
                setData(data)
                setRefreshFlag(refreshFlag)
            })
            .show()
    }
}

//追加任务
internal fun appendTask(
    viewModel: RecorderCardViewModel,
    filterTask: List<String>,
    item: NfcBindItemBO,
    onSuccess: () -> Unit
) = showResourceList(
    type = ResourceType.TASK,
    multiSelect = true,
    filterTask = filterTask,//屏蔽已有任务
    listener = object : CallbackWithData<Any> {
        override fun success(data: Any) {
            super.success(data)
            data as List<TaskItemBO>
            getConfirmDlg(
                "", "确定要添加任务吗？",
                dismissOnBackPressed = false,
                dismissOnTouchOutside = false,
                confirmListener = object :
                    SuccessCallback {
                    override fun success() {
                        super.success()
                        viewModel.updateTaskInfo(
                            data.map { it.task_config.id },
                            item.nfc,
                            AttachResourceType.getType(
                                item.category
                            ),
                            item.title,
                            object : SuccessCallback {
                                override fun success() {
                                    super.success()
                                    toastCenter("任务添加成功")
                                    onSuccess()
                                }
                            },
                            append = true
                        )
                    }
                })?.show()
        }
    }
)